<template>
  <div class="grid-container">
    <!-- 网格布局容器 -->
    <grid-layout
      :layout="layout"
      :col-num="12"
      :row-height="SquareSize"
      :is-draggable="true"
      :is-resizable="true"
      :is-mirrored="false"
      :vertical-compact="true"
      :margin="[BoxGap, BoxGap]"
      :use-css-transforms="true"
      @layout-updated="onLayoutUpdated"
    >
      <!-- 网格项 -->
      <grid-item
        v-for="item in layout"
        :key="item.i"
        :x="item.x"
        :y="item.y"
        :w="item.w"
        :h="item.h"
        :i="item.i"
        :static="item.static || false"
      >
        <div
          class="grid-item-content"
          @contextmenu.stop="handleRightClick($event, getItemData(item.i))"
        >
          <!-- 图标内容 -->
          <div
            @click.stop="jump(getItemData(item.i))"
            class="square"
            :style="innerStyle(item)"
          >
            <img
              class="img"
              :src="getItemData(item.i).src"
              :alt="getItemData(item.i).name"
              v-if="!getItemData(item.i).iconname && getItemData(item.i).src"
            />
            <div
              v-else
              class="icon-background"
              :style="{ backgroundColor: getItemData(item.i).backgroundColor }"
            >
              <div class="icon-text">{{ getItemData(item.i).iconname }}</div>
            </div>
          </div>
        </div>
      </grid-item>

      <!-- 新增网址项 -->
      <grid-item
        v-if="showaddurl.value"
        :x="newItemX"
        :y="newItemY"
        :w="newItemW"
        :h="newItemH"
        :i="'add-item'"
        :static="true"
      >
        <div class="grid-item-content" @click="handleAddNew">
          <div class="square" :style="innerStyle({ w: 1, h: 1 })">
            <div class="icon-background" style="background-color: #f0f0f0">
              <div class="icon-text">+</div>
            </div>
          </div>
        </div>
      </grid-item>
    </grid-layout>
  </div>
</template>

<script setup>
import { computed, defineProps, inject, ref, watch, defineEmits } from "vue";
import { useStore } from "vuex";

// 初始化布局数据
const layout = ref([]);

const emit = defineEmits(["remove", "update:data", "add"]);

const store = useStore();
const props = defineProps({
  id: String,
  data: {
    type: Array,
    default: () => [],
  },
});

/* 基础配置 */
const SquareSize = computed(() => {
  const size = store.getters["getsquareSize"];
  return size > 30 ? size : 100;
});
const BoxGap = computed(() => {
  const gap = store.getters["getboxgap"];
  return gap >= 0 ? gap : 10;
});
const radius = computed(() => store.getters["getradius"]);
const showaddurl = computed(() => store.getters["getshowaddurl"]);

// 初始化布局
const initLayout = () => {
  try {
    const newLayout = props.data.map((item) => {
      // 从数据中提取布局信息
      if (item.layout && typeof item.layout === "object") {
        return {
          i: item.layout.i || item.id,
          x: Number(item.layout.x) || 0,
          y: Number(item.layout.y) || 0,
          w: Number(item.layout.w) || 1,
          h: Number(item.layout.h) || 1,
          static: Boolean(item.layout.static) || false,
        };
      }

      // 兼容处理和默认值
      const [w, h] = (item.size || "1x1").split("x").map(Number);
      return {
        i: item.id,
        x: (layout.value.length * w) % 12,
        y: Math.floor(layout.value.length / (12 / w)),
        w: w || 1,
        h: h || 1,
        static: false,
      };
    });
    layout.value = newLayout;
  } catch (error) {
    console.error("布局初始化失败:", error);
  }
};

// 监听数据变化重新初始化布局
watch(() => props.data, initLayout, { immediate: true, deep: true });

// 新增项的布局参数
const newItemW = 1;
const newItemH = 1;
const newItemX = computed(() => {
  return layout.value.length % 12;
});
const newItemY = computed(() => {
  return layout.value.length > 0
    ? Math.max(...layout.value.map((item) => item.y + item.h))
    : 0;
});

/* 样式计算 */
function innerStyle(layoutItem) {
  return {
    width: `${
      layoutItem.w * SquareSize.value + (layoutItem.w - 1) * BoxGap.value
    }px`,
    height: `${
      layoutItem.h * SquareSize.value + (layoutItem.h - 1) * BoxGap.value
    }px`,
    borderRadius: `${radius.value}px`,
  };
}

/* 数据映射 - 通过id获取原始数据 */
function getItemData(id) {
  if (id === "add-item") {
    return {
      name: "新增网址",
      url: "",
      add: true,
      src: chrome.runtime.getURL("assets/icon/yandex.svg"),
      size: "1x1",
      backgroundColor: "#f0f0f0",
    };
  }
  return props.data.find((item) => item.id === id) || {};
}

/* 布局更新时触发 */
const onLayoutUpdated = (newLayout) => {
  console.log("布局已更新:", newLayout);
  layout.value = newLayout;

  // 更新原始数据中的布局信息
  const updatedData = props.data.map((item) => {
    const itemLayout = newLayout.find((l) => l.i === item.id);
    return itemLayout
      ? {
          ...item,
          layout: { ...itemLayout },
        }
      : item;
  });
  emit("update:data", updatedData);
};

/* 事件处理 */
const showContextMenu = inject("showContextMenu");
const menuItems = [
  {
    label: "编辑",
    action: (data) => {
      emit("update:data", { ...data, isEditing: true });
    },
  },
  {
    label: "删除",
    action: (data) => {
      removeItem(data.id);
    },
  },
  {
    label: "布局",
    Children: ["1x1", "1x2", "2x1", "2x2", "2x4"],
    action: (data, size) => {
      const [w, h] = size.split("x").map(Number);
      const itemIndex = layout.value.findIndex((i) => i.i === data.id);
      if (itemIndex !== -1) {
        layout.value[itemIndex].w = w;
        layout.value[itemIndex].h = h;
        // 触发布局更新
        onLayoutUpdated([...layout.value]);

        const newData = props.data.map((d) =>
          d.id === data.id ? { ...d, size } : d
        );
        emit("update:data", newData);
      }
    },
  },
  {
    label: "固定",
    action: (data) => {
      const item = layout.value.find((i) => i.i === data.id);
      if (item) {
        item.static = !item.static;
        onLayoutUpdated([...layout.value]);

        const newData = props.data.map((d) =>
          d.id === data.id
            ? {
                ...d,
                layout: { ...d.layout, static: !d.layout?.static },
              }
            : d
        );
        emit("update:data", newData);
      }
    },
  },
];

function handleRightClick(e, itemData) {
  e.preventDefault();
  if (itemData.add) return;
  showContextMenu(e, menuItems, itemData);
}

// 移除项
const removeItem = (id) => {
  layout.value = layout.value.filter((item) => item.i !== id);
  emit("remove", id);
};

// 添加新项
const handleAddNew = () => {
  emit("add");
};

// 点击跳转 - 添加拖拽状态判断
const newtab = computed(() => store.getters["getnewtab"]);
function jump(el) {
  // 如果是拖拽状态，则不执行点击逻辑
  if (el.add) return;
  if (el.url) {
    newtab.value ? window.open(el.url, "_blank") : (location.href = el.url);
  }
}
</script>

<style scoped>
.grid-container {
  width: 100%;
  height: 100%;
  overflow: auto;
  box-sizing: border-box;
  padding: 10px;
}

:deep(.vue-grid-layout) {
  position: relative !important;
}

:deep(.vue-grid-item) {
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.grid-item-content {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.square {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  width: 100%;
  height: 100%;
  position: relative;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.square:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.square .img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.icon-background {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-text {
  color: rgba(0, 0, 0, 0.87);
  font-size: 16px;
  font-weight: bold;
  word-wrap: break-word;
  padding: 5px;
  text-align: center;
}

/* 固定项标识 */
:deep(.vue-grid-item.static) .square::after {
  content: "固定";
  position: absolute;
  top: 30px;
  left: 5px;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  color: #333;
}

:deep(.vue-draggable-handle) {
  display: block !important;
}
</style>
